package com.sp.udp;

import java.io.IOException;
import java.net.*;

/**
 * UDP发送端
 *
 * 说明:
 * 1. 没有明确的服务端和客户端, 演变成数据的发送端和接收端
 * 2. 接收数据和发送数据是通过DatagramSocket对象完成的
 * 3. 将数据封装到DatagramPacket对象, 需要进行拆包, 取出数据
 * 4. 当接收到DatagramPacket对象, 需要进行拆包, 取出数据
 * 5. DatagramSocket可以指定再那个端口接收数据
 */
public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9998);
        byte[] data = "hello 明天吃火锅".getBytes();
        DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.0.101"), 9999);

        datagramSocket.send(packet);

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);

        datagramSocket.receive(packet);

        int length = packet.getLength();
        data = packet.getData();
        String s = new String(data, 0, length);
        System.out.println(s);

        datagramSocket.close();
        System.out.println("B端退出");

    }
}
